﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using ServiceStack.Text;
using System.Net.Http.Headers;
using ConsoleApp.Classex;

namespace ConsoleApp
{
    public class demo_httpclient
    {
        public static void demo()
        {
            string url = "http://127.0.0.1/bbapi";

            int max = 0; int wait = 0;
            ThreadPool.GetMaxThreads(out max, out wait);
            ThreadPool.GetAvailableThreads(out max, out wait);
            ThreadPool.SetMaxThreads(200, 185);

            WebRequestHandler handler = new WebRequestHandler();
            handler.UseCookies = true;
            handler.CookieContainer = new CookieContainer();
            handler.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
            HttpClient _client = new HttpClient(handler);
            HttpResponseMessage rsm = _client.GetAsync("https://wx.abchina.com/WebSite/CardStatusAuthenticationAct.ebf").Result;

            List<Cookie> cookies = handler.CookieContainer.ToListCookie();
            foreach (var item in cookies)
            {
                Console.WriteLine(item.Name + "=" + item.Value);
            }

            HttpResponseHeaders heads = rsm.Headers;
            foreach (var head in heads)
            {
                Console.WriteLine(head.Key + "=" + head.Value);
            }
            return;

            for (int i = 0; i < 1000; i++)
            {
                int temp = i;
                ThreadPool.QueueUserWorkItem(x =>
                {
                    try
                    {
                        Console.WriteLine(Thread.CurrentThread.Name + "---" + url.GetStringFromUrl() + "---" + temp);
                    }
                    catch (Exception ex)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine(ex.Message);
                        Console.ResetColor();
                    }
                });
            }
        }

        private static void ZhaoshanQuery()
        {
            IDictionary<string, string> IdentityType = new Dictionary<string, string>();
            IdentityType.Add("01", "身份证");
            IdentityType.Add("02", "护照");
            IdentityType.Add("03", "其他");

            WebRequestHandler handler = new WebRequestHandler();
            handler.UseCookies = true;
            handler.CookieContainer = new CookieContainer();
            handler.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
            HttpClient _client = new HttpClient(handler);
            _client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36");
            _client.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            _client.DefaultRequestHeaders.Add("Accept-Encoding", "gzip,deflate,sdch");
            _client.DefaultRequestHeaders.Add("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6,nl;q=0.4,zh-TW;q=0.2");
            _client.DefaultRequestHeaders.Add("Connection", "keep-alive");
            _client.DefaultRequestHeaders.Add("Host", "ccclub.cmbchina.com");
            _client.DefaultRequestHeaders.Add("Origin", "https://ccclub.cmbchina.com");
            _client.DefaultRequestHeaders.Add("Referer", "https://ccclub.cmbchina.com/mca/MQuery.aspx");

            string getresponse = _client.GetStringAsync("https://ccclub.cmbchina.com/mca/MQuery.aspx").Result;

            byte[] picbyte = _client.GetByteArrayAsync("https://ccclub.cmbchina.com/mca/~/cmb/antifloodimgs.ashx?rnd=0.8941568625159562").Result;
            string pic64 = Convert.ToBase64String(picbyte);
            var postdata = new FormUrlEncodedContent(new Dictionary<string, string>()
            {
                {"base64String", pic64},
                {"codeType","1004"},
                {"source","bkjd"},
            });
            HttpClient client = new HttpClient();
            HttpResponseMessage response = client.PostAsync("http://open.51zhangdan.com/uuwise_interface/dmservice", postdata).Result;
            string rs = response.Content.ReadAsStringAsync().Result; //status:1,codeId:188285410&ddd2,result:4716
            string extraCode = rs.Substring(rs.Length - 4, 4);

            string json = string.Empty;
            using (StringWriter sw = new StringWriter())
            {
                using (JsonWriter jw = new JsonTextWriter(sw))
                {
                    jw.WriteStartObject();
                    jw.WritePropertyName("cardtype");
                    jw.WriteValue("01");
                    jw.WritePropertyName("cardid");
                    jw.WriteValue("330725198212285019");
                    jw.WritePropertyName("extracode");
                    jw.WriteValue(extraCode);
                    jw.WriteEndObject();
                    json = sw.GetStringBuilder().ToString();
                }
            }

            StringContent postjson = new StringContent(json, Encoding.UTF8);
            postjson.Headers.Remove("Content-Type");
            postjson.Headers.Add("Content-Type", "application/json; charset=UTF-8");

            response = _client.PostAsync("https://ccclub.cmbchina.com/mca/Service/CWAService.asmx/QuerySchedule", postjson).Result;
            response.Content.Headers.Remove("Content-Type");
            response.Content.Headers.Add("Content-Type", "application/json; charset=gb2312");
            rs = response.Content.ReadAsStringAsync().Result;
        }

        public static void vote()
        {
            string getresponse = string.Empty;
            StringBuilder sb = new StringBuilder(getresponse);

            string proxy = string.Empty;
            using (HttpClient ht = new HttpClient())
            {
                proxy = ht.GetStringAsync("http://monitor.51zhangdan.com/monitor/manage/proxy/ip.do").Result.Replace("\"", "");
            }

            WebRequestHandler handler = new WebRequestHandler();
            handler.UseCookies = true;
            handler.CookieContainer = new CookieContainer();
            handler.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
            handler.UseProxy = true;
            handler.Proxy = new WebProxy(proxy, true);
            HttpClient _client = new HttpClient(handler);
            _client.GetStringAsync("http://loupan.cbfw.cn/toupiao/tp12pc").ContinueWith(z =>
            {
                getresponse = z.Result;

                var postdata = new FormUrlEncodedContent(new Dictionary<string, string>()
                {
                    {"id", "1301"}
                });

                _client.DefaultRequestHeaders.Add("Accept", "application/json, text/javascript, */*");
                _client.DefaultRequestHeaders.Add("Accept-Encoding", "gzip,deflate,sdch");
                _client.DefaultRequestHeaders.Add("Accept-Language", "zh-CN,zh;q=0.8");
                _client.DefaultRequestHeaders.Add("Connection", "keep-alive");
                _client.DefaultRequestHeaders.Add("Host", "loupan.cbfw.cn");
                _client.DefaultRequestHeaders.Add("Origin", "http://loupan.cbfw.cn");
                _client.DefaultRequestHeaders.Add("Referer", "http://loupan.cbfw.cn/toupiao/tp12pc");
                _client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36");
                _client.DefaultRequestHeaders.Add("X-Requested-With", "XMLHttpRequest");

                _client.PostAsync("http://loupan.cbfw.cn/toupiao/tp12cptp", postdata).ContinueWith(x =>
                {
                    HttpResponseMessage rsm = x.Result;
                    rsm.Content.Headers.Remove("Content-Type");
                    rsm.Content.Headers.Add("Content-Type", "application/json; charset=gb2312");

                    getresponse = rsm.Content.ReadAsStringAsync().Result;
                    sb = new StringBuilder(getresponse);
                    Console.WriteLine(getresponse);
                });
            }).ContinueWith(t =>
            {
                foreach (Exception item in t.Exception.InnerExceptions)
                {
                    Console.WriteLine("异常类型：{0}\r\n来自：{1}\r\n异常内容：{2}", item.GetType(), item.Source, item.Message);
                }
            }, TaskContinuationOptions.OnlyOnFaulted);
        }
    }
}